// pages/goods_detail/index.js
const MoneyUtils = require('../../utils/money.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0, // 导航栏总高度 = 状态栏高度 + 导航栏高度
    contentTop: 0, // 内容区域top位置
    goodsId: 0, // 商品ID
    goodsData: null, // 商品详情数据
    isCollected: false, // 是否已收藏
    showShareModal: false, // 是否显示分享弹窗
    currentImageIndex: 0, // 当前轮播图索引
    selectedSpec: {}, // 选中的规格
    quantity: 1, // 购买数量
    showSpecModal: false, // 是否显示规格选择弹窗
    bottomSafeArea: 0, // 底部安全区域高度
    actionType: '' // 操作类型：buy_now 立即购买，add_cart 加入购物车
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取商品ID
    const goodsId = options.id || 1
    console.log('商品详情页加载，商品ID:', goodsId)
    
    // 计算导航栏高度和底部安全区域
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight
    const navBarHeight = statusBarHeight + 44 // 44是导航栏内容高度
    const bottomSafeArea = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
    
    this.setData({
      navBarHeight,
      contentTop: navBarHeight,
      goodsId: goodsId,
      bottomSafeArea
    })
    
    // 根据商品ID加载详情数据
    this.loadGoodsDetail(goodsId)
    
    // 检查收藏状态
    this.checkCollectionStatus()
    
    // 启用分享菜单
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 加载商品详情数据
   */
  async loadGoodsDetail(goodsId) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })

      // 从云数据库获取商品详情
      const db = wx.cloud.database()
      const result = await db.collection('goods').doc(goodsId).get()

      console.log('商品详情获取结果：', result)

      if (result.data) {
        const goodsData = result.data
        
        // 处理商品数据，确保字段兼容和金额精度
        const processedGoodsData = {
          id: goodsData._id || goodsData.id,
          name: goodsData.name,
          subtitle: goodsData.description || '',
          images: goodsData.images || [goodsData.image],
          detailImages: goodsData.detailImages || goodsData.images || [goodsData.image],
          price: MoneyUtils.formatAmount(goodsData.price),
          originalPrice: MoneyUtils.formatAmount(goodsData.originalPrice || goodsData.price),
          sales: goodsData.sales || 0,
          stock: goodsData.stock || 0,
          tags: goodsData.tags || [],
          rating: 4.8, // 默认评分
          reviewCount: goodsData.sales || 0,
          description: goodsData.details || goodsData.description || '',
          comments: this.formatComments(goodsData.comments || []), // 格式化评论数据
          features: [
            `分类：${goodsData.category}`,
            `库存：${goodsData.stock || 0}件`,
            `销量：${goodsData.sales || 0}件`,
            '品质保证，正品保障'
          ],
          specifications: goodsData.specifications ? 
            goodsData.specifications.map(spec => ({
              name: spec.name,
              options: spec.options.map(option => ({
                name: option,
                price: 0,
                stock: goodsData.stock || 0
              })),
              offset: spec.offset || [] // 保留原始的offset数据
            })) : [
              {
                name: "数量",
                options: [
                  { name: "1件", price: 0, stock: goodsData.stock || 0 }
                ],
                offset: [0]
              }
            ],
          details: [
            {
              title: "商品详情",
              content: [
                `商品名称：${goodsData.name}`,
                `商品分类：${goodsData.category}`,
                `商品价格：¥${goodsData.price}`,
                `库存数量：${goodsData.stock || 0}件`,
                `销售数量：${goodsData.sales || 0}件`
              ]
            }
          ],
          shop: {
            name: "优AI文化商城",
            rating: 4.9,
            followers: 12580
          }
        }
        
        // 初始化默认规格选择
        const selectedSpec = {}
        if (processedGoodsData.specifications && processedGoodsData.specifications.length > 0) {
          processedGoodsData.specifications.forEach(spec => {
            if (spec.options && spec.options.length > 0) {
              selectedSpec[spec.name] = spec.options[0]
            }
          })
        }
        
        this.setData({
          goodsData: processedGoodsData,
          selectedSpec: selectedSpec,
          currentPrice: MoneyUtils.formatAmount(processedGoodsData.price),
          currentPriceFormatted: MoneyUtils.formatAmount(processedGoodsData.price).toFixed(2)
        })

        // 计算初始价格
        this.calculateCurrentPrice()

        console.log('商品详情加载成功：', processedGoodsData)
        console.log('默认选中规格：', selectedSpec)
        console.log('规格数据：', processedGoodsData.specifications)
      } else {
        throw new Error('商品不存在')
      }
    } catch (error) {
      console.error('加载商品详情失败：', error)
      wx.showToast({
        title: '商品加载失败',
        icon: 'none',
        duration: 2000
      })
      
      // 延迟返回上一页
      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
    } finally {
      wx.hideLoading()
    }
  },

  /**
   * 轮播图切换事件
   */
  onSwiperChange(e) {
    this.setData({
      currentImageIndex: e.detail.current
    })
  },

  /**
   * 收藏/取消收藏
   */
  async toggleCollect() {
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }

    try {
      wx.showLoading({
        title: '处理中...',
        mask: true
      })

      const action = this.data.isCollected ? 'remove' : 'add'
      const result = await wx.cloud.callFunction({
        name: 'toggleCollection',
        data: {
          itemId: this.data.goodsId,
          itemType: 'goods',
          action: action
        }
      })

      if (result.result && result.result.success) {
        const isCollected = result.result.isCollected
        this.setData({
          isCollected
        })
        
        wx.showToast({
          title: result.result.message,
          icon: 'success',
          duration: 1500
        })
      } else {
        wx.showToast({
          title: result.result?.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('收藏操作失败：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },


  /**
   * 预览图片
   */
  previewImage(e) {
    const current = e.currentTarget.dataset.src
    const urls = this.data.goodsData.images
    
    wx.previewImage({
      current,
      urls
    })
  },

  /**
   * 选择规格
   */
  selectSpec(e) {
    const { specName, option } = e.currentTarget.dataset
    console.log('选择规格:', specName, option)
    const selectedSpec = { ...this.data.selectedSpec }
    selectedSpec[specName] = option
    
    this.setData({
      selectedSpec
    })
    
    // 重新计算价格
    this.calculateCurrentPrice()
  },

  /**
   * 数量减少
   */
  decreaseQuantity() {
    const quantity = Math.max(1, this.data.quantity - 1)
    this.setData({ quantity })
  },

  /**
   * 数量增加
   */
  increaseQuantity() {
    const maxQuantity = this.data.goodsData.stock
    const quantity = Math.min(maxQuantity, this.data.quantity + 1)
    this.setData({ quantity })
  },

  /**
   * 显示规格选择弹窗
   */
  showSpecModal(e) {
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }
    
    const actionType = e.currentTarget.dataset.type
    this.setData({
      showSpecModal: true,
      actionType
    })
  },

  /**
   * 关闭规格选择弹窗
   */
  closeSpecModal() {
    this.setData({
      showSpecModal: false
    })
  },

  /**
   * 检查登录状态
   */
  checkLoginStatus() {
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    const userInfo = wx.getStorageSync('userInfo')
    
    if (!isLoggedIn || !userInfo) {
      wx.showModal({
        title: '需要登录',
        content: '请先登录后再进行此操作',
        confirmText: '去登录',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/index'
            })
          }
        }
      })
      return false
    }
    
    return true
  },


  /**
   * 加入购物车
   */
  async addToCart() {
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }
    
    try {
      wx.showLoading({
        title: '加入购物车中...',
        mask: true
      })
      
      const { goodsData, selectedSpec, quantity } = this.data
      const currentPrice = this.getCurrentPrice()
      
      // 构建购物车商品信息，确保金额精度
      const cartItem = {
        productId: goodsData.id,
        name: goodsData.name,
        price: MoneyUtils.formatAmount(currentPrice),
        basePrice: MoneyUtils.formatAmount(goodsData.price),
        quantity: quantity,
        image: goodsData.images[0],
        specifications: this.getSelectedSpecText(),
        selectedSpec: selectedSpec
      }
      
      // 调用云函数添加到购物车
      const result = await wx.cloud.callFunction({
        name: 'addToCart',
        data: cartItem
      })
      
      if (result.result && result.result.success) {
        wx.showToast({
          title: '已加入购物车',
          icon: 'success',
          duration: 1500
        })
        this.closeSpecModal()
      } else {
        wx.showToast({
          title: result.result?.message || '加入购物车失败',
          icon: 'none',
          duration: 2000
        })
      }
    } catch (error) {
      console.error('加入购物车失败：', error)
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      })
    } finally {
      wx.hideLoading()
    }
  },

  /**
   * 立即购买
   */
  buyNow() {
    // 检查登录状态
    if (!this.checkLoginStatus()) {
      return
    }
    
    const { goodsData, selectedSpec, quantity } = this.data
    const currentPrice = this.getCurrentPrice()
    
    // 构建订单商品信息，确保金额精度
    const orderItem = {
      productId: goodsData.id,
      name: goodsData.name,
      price: MoneyUtils.formatAmount(currentPrice), // 使用计算后的价格
      basePrice: MoneyUtils.formatAmount(goodsData.price), // 保存基础价格
      quantity: quantity,
      image: goodsData.images[0],
      specifications: this.getSelectedSpecText(),
      selectedSpec: selectedSpec // 保存选中的规格信息
    }
    
    // 跳转到订单填写页面
    wx.navigateTo({
      url: `/pages/order_create/index?orderData=${encodeURIComponent(JSON.stringify([orderItem]))}`
    })
    
    this.closeSpecModal()
  },

  /**
   * 获取选中规格的文本描述
   */
  getSelectedSpecText() {
    const selectedSpec = this.data.selectedSpec
    const specTexts = []
    
    for (const specName in selectedSpec) {
      if (selectedSpec[specName] && selectedSpec[specName].name) {
        specTexts.push(`${specName}: ${selectedSpec[specName].name}`)
      }
    }
    
    return specTexts.join(', ') || '默认规格'
  },

  /**
   * 计算当前选中规格的价格
   */
  calculateCurrentPrice() {
    const { goodsData, selectedSpec } = this.data
    if (!goodsData || !goodsData.specifications) {
      const basePrice = MoneyUtils.formatAmount(goodsData?.price || 0)
      this.setData({
        currentPrice: basePrice,
        currentPriceFormatted: basePrice.toFixed(2)
      })
      return basePrice
    }

    let totalOffset = 0
    const specifications = goodsData.specifications

    // 遍历每个规格类型
    specifications.forEach(spec => {
      if (spec.offset && selectedSpec[spec.name]) {
        // 找到选中选项的索引
        const selectedOptionName = selectedSpec[spec.name].name
        const optionIndex = spec.options.findIndex(option => 
          (typeof option === 'string' ? option : option.name) === selectedOptionName
        )
        
        // 如果找到对应的偏移量，累加到总偏移量
        if (optionIndex !== -1 && spec.offset[optionIndex] !== undefined) {
          totalOffset = MoneyUtils.add(totalOffset, spec.offset[optionIndex])
        }
      }
    })

    const basePrice = MoneyUtils.formatAmount(goodsData.price || 0)
    const currentPrice = MoneyUtils.add(basePrice, totalOffset)
    
    // 更新显示的价格
    this.setData({
      currentPrice: MoneyUtils.formatAmount(currentPrice),
      currentPriceFormatted: MoneyUtils.formatAmount(currentPrice).toFixed(2)
    })

    return MoneyUtils.formatAmount(currentPrice)
  },

  /**
   * 获取当前选中规格的价格
   */
  getCurrentPrice() {
    return this.data.currentPrice || this.data.goodsData?.price || 0
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查是否从登录页面返回，如果已登录且之前有购买意图，可以提示用户继续购买
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    if (isLoggedIn && this.data.goodsData) {
      // 用户已登录，可以进行购买操作
      console.log('用户已登录，可以进行购买操作')
    }
    
    // 重新检查收藏状态
    this.checkCollectionStatus()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.goodsData.name,
      path: `/pages/goods_detail/index?id=${this.data.goodsId}`
    }
  },

  /**
   * 返回按钮点击事件
   */
  handleBack() {
    wx.navigateBack()
  },

  /**
   * 跳转到购物车页面
   */
  goToCart() {
    wx.navigateTo({
      url: '/pages/cart/index'
    })
  },

  /**
   * 检查收藏状态
   */
  async checkCollectionStatus() {
    // 如果用户未登录，跳过状态检查
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    if (!isLoggedIn) {
      return
    }

    try {
      const result = await wx.cloud.callFunction({
        name: 'getCollectionStatus',
        data: {
          itemId: this.data.goodsId,
          itemType: 'goods'
        }
      })

      if (result.result && result.result.success) {
        this.setData({
          isCollected: result.result.isCollected
        })
        console.log('商品收藏状态:', result.result.isCollected)
      }
    } catch (error) {
      console.error('获取商品收藏状态失败：', error)
    }
  },

  /**
   * 格式化评论数据
   */
  formatComments(comments) {
    if (!comments || !Array.isArray(comments)) {
      return []
    }
    
    return comments.map(comment => {
      return {
        ...comment,
        formattedTime: this.formatTime(comment.createdAt),
        rating: Math.max(1, Math.min(5, comment.rating || 5)) // 确保评分在1-5之间
      }
    })
  },

  /**
   * 格式化时间显示
   */
  formatTime(timestamp) {
    if (!timestamp) return '未知时间'
    
    const now = new Date()
    const commentTime = new Date(timestamp)
    const diffTime = now.getTime() - commentTime.getTime()
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))
    const diffHours = Math.floor(diffTime / (1000 * 60 * 60))
    const diffMinutes = Math.floor(diffTime / (1000 * 60))
    
    if (diffDays > 30) {
      // 超过30天显示具体日期
      return commentTime.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    } else if (diffDays > 0) {
      return `${diffDays}天前`
    } else if (diffHours > 0) {
      return `${diffHours}小时前`
    } else if (diffMinutes > 0) {
      return `${diffMinutes}分钟前`
    } else {
      return '刚刚'
    }
  },

  /**
   * 阻止事件冒泡
   */
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
})